#coding:utf-8
'''
create on 2017-04-20

@author: sandy
'''
import sys,platform
sys.path.append("../")
from twisted.internet import reactor
from pycommon import Daemon
from pycommon import LogManager
from pycommon import Utils
from pycommon import RemoteManager
import os
import random
import time
import logging
import Center
import ServerConfig
import ClientFactory
import TimeCheck
import HallManager
import UserManager
import HallConfig
import Game

if 'twisted.internet.reactor' not in sys.modules: 
    if platform.system() == "Linux":
        from twisted.internet import epollreactor
        epollreactor.install()  
    else:
        from twisted.internet import iocpreactor
        iocpreactor.install()


def ServerStart(isdaemon):
    logging.info("############Start GameServer############")
    random.seed(time.time())        
    patchdir = os.path.join(ServerConfig.instance.rundir, u"patch")
    sys.path.append(patchdir)
    TimeCheck.instance.start()
    HallManager.instance.start()
    UserManager.instance.start()
    Center.instance.start(ServerConfig.instance.center_ip,ServerConfig.instance.center_port)
    ClientFactory.instance.start(ServerConfig.instance.server_ip,ServerConfig.instance.server_port,ServerConfig.instance.max_client)
    
def ServerStop():
    Center.instance.stop();
    ClientFactory.instance.stop()
    UserManager.instance.stop()
    HallManager.instance.stop()
    TimeCheck.instance.stop()
    Game.stop()

def getConfig(isdaemon):
    Game.start()
    configlist = RemoteManager.instance.getConfigList()
    RemoteManager.instance.requestConfig(configlist,ServerStart,isdaemon)

def getServerConfig(isdaemon):
    configlist = [u'server%d.*' % RemoteManager.instance.sid]
    RemoteManager.instance.addConfigCallback(ServerConfig.instance)
    RemoteManager.instance.addConfigCallback(HallConfig.instance)
    RemoteManager.instance.requestConfig(configlist,getConfig,isdaemon)

def daemonFunc(isdaemon):
    LogManager.instance.setupLog(RemoteManager.instance.loglevel,RemoteManager.instance.logfile,isdaemon)
    logging.info("############Update GameServer Config############")
    RemoteManager.instance.start(getServerConfig,isdaemon)
    reactor.run()
    ServerStop()

def run():
    sid, msip, msport, pidpath, logfile, loglevel, pathSelfConfig = Utils.loadDaemonConfig(ServerConfig.instance.rundir)
    RemoteManager.instance.init(sid,msip,msport,logfile, loglevel)
    Daemon.run(pidpath, daemonFunc)

if __name__ == "__main__":
    run()